// 第三方支付相关
import { post } from '@common/ajax';
import { basePath } from '@router/config';
import urls from '@common/url';
import { setPayTypeAndResult } from '@biztools/info';
import logger from '@common/logger';

const formSubmit = (info) => {
    const form = document.createElement('form');
    const formData = info.body;
    for (let item in formData) {
        const el = createInput('text', item, formData[item]);
        form.appendChild(el);
    }
    form.method = info.method;
    form.action = info.url;
    document.querySelector('body').appendChild(form);
    form.submit();
};

const createInput = (type, name, value) => {
    const inputEl = document.createElement('input');
    inputEl.type = type;
    inputEl.name = name;
    inputEl.value = value;
    return inputEl;
};

/**
 * 执行第三方充值跳转支付
 * @param {String} orderNumber 订单号
 * @param {Number} thirdType 第三方跳转的类型，1-盛付通 2-收钱吧，默认为：1
 * @param {Object} exts 扩展参数
 */
export const thirdPayRechargeRedirectInfo = async (orderNumber, thirdType=1, exts={} ) => {
    const backUrl = `${window.location.origin}${basePath}/member/pay-result?orderNumber=${orderNumber}`;
    const res = await post(urls.thirdRechargeRedirectInfo, {
        order_number: orderNumber,
        url: backUrl,
        store_id: '',
        extras: exts,
    });
    logger.success('第三方支付接口返回的参数：', res);
    runThirdPay(res, thirdType);
};

/**
 * 执行第三方订单跳转支付
 * @param {String} orderNumber 订单号
 * @param {Number} thirdType 第三方跳转的类型，1-盛付通 2-收钱吧，默认为：1
 * @param {Object} param 营销信息参数参数
 * @param {Object} exts 扩展参数
 */
export const thirdPayOrderRedirectInfo = async (orderNumber, thirdType=1, param, exts={}) => {
    setPayTypeAndResult(true, '3001');
    const backUrl = `${window.location.origin}${basePath}/order/detail/${orderNumber}?`;
    const res = await post(`${urls.thirdOrderRedirectInfo}/${orderNumber}/redirect`, {
        url: backUrl,
        exts,
        ...param,
    });
    runThirdPay(res, thirdType);
};

/**
 * 执行第三方支付
 * @param {Object} res 支付返回的详情
 * @param {Number} type 第三方类型
 */
const runThirdPay = (res, type) => {
    switch(type) {
    case 1: // 盛付通
        res && formSubmit(res);
        break;
    case 2: // 收钱吧
        window.location.href = res.url;
    }
};

/**
 * 判断是否第三方支付成功
 * @param {Object} param
 */
export const checkThirdPayResult = (param) => {
    const { is_success, status, payResult } = param;
    // 收钱吧
    if (`${is_success}` === 'T' && `${status}` === 'FAIL') {
        return false;
    }
    // 盛付通
    if (`${payResult}` === 'false') {
        return false;
    }
    return true;
};
